<template>
  <view class="test-page">
    <view class="header">
      <text class="title">修复后的订阅消息测试</text>
      <text class="subtitle">验证412错误修复效果</text>
    </view>

    <!-- 测试步骤 -->
    <view class="test-section">
      <view class="step-card">
        <view class="step-title">步骤1: 订阅消息模板</view>
        <button class="test-btn primary" @click="subscribeMessage" :loading="subscribing">
          {{ subscribing ? '订阅中...' : '🔔 订阅消息' }}
        </button>
        <view class="result" v-if="subscribeResult">
          <text :class="subscribeResult.success ? 'success' : 'error'">
            {{ subscribeResult.message }}
          </text>
        </view>
      </view>

      <view class="step-card">
        <view class="step-title">步骤2: 测试发送（修复后）</view>
        <button class="test-btn success" @click="testFixedSend" :loading="testing">
          {{ testing ? '发送中...' : '🚀 测试修复后的发送' }}
        </button>
        <view class="result" v-if="testResult">
          <text :class="testResult.success ? 'success' : 'error'">
            {{ testResult.message }}
          </text>
          <view class="details" v-if="testResult.details">
            <text class="details-text">{{ testResult.details }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 对比测试 -->
    <view class="compare-section">
      <view class="compare-title">对比测试</view>
      <view class="compare-buttons">
        <button class="test-btn default" @click="testOldSend" :loading="testingOld">
          旧版本发送
        </button>
        <button class="test-btn primary" @click="testFixedSend" :loading="testing">
          修复版发送
        </button>
      </view>
    </view>

    <!-- 结果显示 -->
    <view class="results-section" v-if="allResults.length > 0">
      <view class="results-title">测试结果历史</view>
      <scroll-view scroll-y class="results-list">
        <view 
          class="result-item" 
          v-for="(item, index) in allResults" 
          :key="index"
          :class="item.success ? 'success-item' : 'error-item'"
        >
          <view class="result-header">
            <text class="result-type">{{ item.type }}</text>
            <text class="result-time">{{ formatTime(item.timestamp) }}</text>
          </view>
          <view class="result-content">
            <text class="result-message">{{ item.message }}</text>
          </view>
          <view class="result-raw" v-if="item.raw">
            <text class="raw-text">原始响应: {{ item.raw }}</text>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      subscribing: false,
      testing: false,
      testingOld: false,
      
      subscribeResult: null,
      testResult: null,
      
      allResults: [],
      
      templateId: 'zvaRsziQ2U139jQdNUSSX8cCgyqHe_r5xIsuGo36wR8'
    }
  },
  
  methods: {
    // 订阅消息
    async subscribeMessage() {
      this.subscribing = true
      this.subscribeResult = null
      
      try {
        // #ifdef MP-WEIXIN
        const result = await uni.requestSubscribeMessage({
          tmplIds: [this.templateId]
        })
        
        console.log('订阅结果:', result)
        
        const status = result[this.templateId]
        
        if (status === 'accept') {
          this.subscribeResult = {
            success: true,
            message: '✅ 订阅成功！请立即测试发送'
          }
          
          this.addResult('订阅', '用户同意订阅', true, JSON.stringify(result))
          
          // 提示立即测试
          setTimeout(() => {
            uni.showModal({
              title: '订阅成功',
              content: '订阅成功！请立即点击"测试修复后的发送"按钮验证效果。',
              showCancel: false
            })
          }, 500)
          
        } else {
          this.subscribeResult = {
            success: false,
            message: '❌ 订阅失败或被拒绝'
          }
          
          this.addResult('订阅', `用户${status}订阅`, false, JSON.stringify(result))
        }
        // #endif
        
        // #ifndef MP-WEIXIN
        this.subscribeResult = {
          success: false,
          message: '⚠️ 非微信小程序环境'
        }
        // #endif
        
      } catch (error) {
        console.error('订阅失败:', error)
        this.subscribeResult = {
          success: false,
          message: `❌ 订阅异常: ${error.message}`
        }
        
        this.addResult('订阅', '订阅异常', false, error.message)
      } finally {
        this.subscribing = false
      }
    },
    
    // 测试修复后的发送
    async testFixedSend() {
      this.testing = true
      this.testResult = null
      
      try {
        const response = await this.callAPI('/wechat/testFixed')
        
        console.log('修复后发送响应:', response)
        
        this.testResult = {
          success: response.success,
          message: response.success ? '🎉 修复后发送成功！' : '❌ 修复后发送失败',
          details: response.message || response.data
        }
        
        this.addResult('修复版发送', response.message || '无消息', response.success, JSON.stringify(response))
        
        if (response.success) {
          uni.showToast({
            title: '发送成功',
            icon: 'success'
          })
        } else {
          uni.showModal({
            title: '发送失败',
            content: `错误信息: ${response.message}`,
            showCancel: false
          })
        }
        
      } catch (error) {
        console.error('测试发送失败:', error)
        this.testResult = {
          success: false,
          message: '❌ 网络错误',
          details: error.message
        }
        
        this.addResult('修复版发送', '网络错误', false, error.message)
      } finally {
        this.testing = false
      }
    },
    
    // 测试旧版本发送（对比用）
    async testOldSend() {
      this.testingOld = true
      
      try {
        const response = await this.callAPI('/wechat/sendConfirmed')
        
        console.log('旧版发送响应:', response)
        
        this.addResult('旧版发送', response.message || '无消息', response.success, JSON.stringify(response))
        
      } catch (error) {
        console.error('旧版测试失败:', error)
        this.addResult('旧版发送', '网络错误', false, error.message)
      } finally {
        this.testingOld = false
      }
    },
    
    // 添加测试结果
    addResult(type, message, success, raw) {
      this.allResults.unshift({
        type,
        message,
        success,
        raw,
        timestamp: Date.now()
      })
      
      // 限制结果数量
      if (this.allResults.length > 10) {
        this.allResults = this.allResults.slice(0, 10)
      }
    },
    
    // 格式化时间
    formatTime(timestamp) {
      const date = new Date(timestamp)
      return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`
    },
    
    // 调用API
    callAPI(endpoint) {
      return new Promise((resolve) => {
        uni.request({
          url: `http://localhost:9090${endpoint}`,
          method: 'GET',
          success: (res) => {
            console.log(`API ${endpoint} 响应:`, res)
            
            resolve({
              success: res.statusCode === 200 && res.data.code === '200',
              message: res.data.message,
              data: res.data.data,
              raw: res
            })
          },
          fail: (error) => {
            console.error(`API ${endpoint} 失败:`, error)
            resolve({
              success: false,
              message: `网络错误: ${error.errMsg}`,
              raw: error
            })
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.test-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20rpx;
}

.header {
  text-align: center;
  padding: 40rpx 0;
  
  .title {
    display: block;
    font-size: 36rpx;
    font-weight: bold;
    color: #fff;
    margin-bottom: 12rpx;
  }
  
  .subtitle {
    display: block;
    font-size: 24rpx;
    color: rgba(255, 255, 255, 0.8);
  }
}

.test-section, .compare-section, .results-section {
  margin-bottom: 30rpx;
}

.step-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
  
  .step-title {
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }
}

.test-btn {
  width: 100%;
  padding: 20rpx;
  border-radius: 12rpx;
  font-size: 28rpx;
  font-weight: bold;
  border: none;
  margin-bottom: 20rpx;
  
  &::after {
    border: none;
  }
  
  &.primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff;
  }
  
  &.success {
    background: linear-gradient(135deg, #43e97b 0%, #38d9a9 100%);
    color: #fff;
  }
  
  &.default {
    background: #f5f5f5;
    color: #666;
  }
  
  &[loading] {
    opacity: 0.7;
  }
}

.result {
  padding: 16rpx 20rpx;
  border-radius: 8rpx;
  background: #f8f9fa;
  
  .success {
    color: #43e97b;
  }
  
  .error {
    color: #ff4757;
  }
  
  .details {
    margin-top: 12rpx;
    
    .details-text {
      font-size: 24rpx;
      color: #666;
    }
  }
}

.compare-section {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
  
  .compare-title {
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
    text-align: center;
  }
  
  .compare-buttons {
    display: flex;
    gap: 20rpx;
    
    .test-btn {
      flex: 1;
      margin-bottom: 0;
    }
  }
}

.results-section {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
  
  .results-title {
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }
  
  .results-list {
    max-height: 600rpx;
    
    .result-item {
      padding: 20rpx;
      border-radius: 12rpx;
      margin-bottom: 16rpx;
      
      &.success-item {
        background: rgba(67, 233, 123, 0.1);
        border-left: 4rpx solid #43e97b;
      }
      
      &.error-item {
        background: rgba(255, 71, 87, 0.1);
        border-left: 4rpx solid #ff4757;
      }
      
      .result-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12rpx;
        
        .result-type {
          font-size: 28rpx;
          font-weight: bold;
          color: #333;
        }
        
        .result-time {
          font-size: 22rpx;
          color: #999;
        }
      }
      
      .result-content {
        .result-message {
          font-size: 26rpx;
          color: #666;
          line-height: 1.4;
        }
      }
      
      .result-raw {
        margin-top: 12rpx;
        padding: 12rpx;
        background: rgba(0, 0, 0, 0.05);
        border-radius: 8rpx;
        
        .raw-text {
          font-size: 20rpx;
          color: #999;
          font-family: monospace;
          word-break: break-all;
        }
      }
    }
  }
}
</style>
